﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace NFinal
{
    /// <summary>
    /// NFinal的控制器基类，核心类，类似于asp.net中的page类
    /// </summary>
    public class OwinAction : Action
    {
        
        public IDictionary<string, object> enviroment;
        public ICookie Cookie;
        public ISession Session;
        private bool beforeWrite = true;
        private Stream contentStream;
        public CompressMode compressMode;
        #region 初始化函数
        public OwinAction() { }
        /// <summary>
        /// Http输出初始化
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="request"></param>
        public OwinAction(IDictionary<string, object> enviroment, Owin.Request request, CompressMode compressMode)
        {
            this.enviroment = enviroment;
            this.request = request;
            this.Cookie = new Cookie(request.cookies);
            this.response.stream = (System.IO.Stream)enviroment["owin.ResponseBody"];
            this.response.headers = new Dictionary<string, string[]>();
            this.response.statusCode = 200;
            this._serverType = ServerType.NFinalOwin;
            SetCompressMode(compressMode);
        }
        /// <summary>
        /// 流输出初始化函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="request"></param>
        /// <param name="compressMode"></param>
        public OwinAction(string fileName, Owin.Request request, CompressMode compressMode)
        {
            this.request = request;
            this.response.stream = new FileStream(fileName,FileMode.Create);
            this.response.headers = new Dictionary<string, string[]>();
            this.response.statusCode = 200;
            this._serverType = ServerType.IsStatic;
            SetCompressMode(compressMode);
        }
        /// <summary>
        /// 流输出初始化函数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="compressMode"></param>
        public OwinAction(System.IO.Stream stream, Owin.Request request, CompressMode compressMode)
        {
            this.request = request;
            this.response.stream = stream;
            this.response.headers = new Dictionary<string, string[]>();
            this.response.statusCode = 200;
            this._serverType = ServerType.IsStatic;
            SetCompressMode(compressMode);
        }
        /// <summary>
        /// 设置压缩方式
        /// </summary>
        /// <param name="compressMode"></param>
        private void SetCompressMode(CompressMode compressMode)
        {
            this.compressMode = compressMode;
            if (compressMode == CompressMode.None)
            {
                this.contentStream = this.response.stream;
            }
            else
            {
                if (compressMode == CompressMode.GZip)
                {
                    this.contentStream = new System.IO.Compression.GZipStream(this.response.stream, System.IO.Compression.CompressionMode.Compress, true);
                    this.response.headers.Add("Content-Encoding", new string[] { "gzip" });
                }
                else if (compressMode == CompressMode.Deflate)
                {
                    this.contentStream = new System.IO.Compression.DeflateStream(this.response.stream, System.IO.Compression.CompressionMode.Compress, true);
                    this.response.headers.Add("Content-Encoding", new string[] { "deflate" });
                }
            }
        }
        #endregion
        #region 输出函数
        /// <summary>
        /// 获取请求头
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public override string GetRequestHeader(string key)
        {
            if (request.headers.ContainsKey(key))
            {
                return request.headers[key][0];
            }
            return null;
        }
        /// <summary>
        /// 设置输出头
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public override void SetResponseHeader(string key, string value)
        {
            this.response.headers.AddValue(key, new string[] { value });
        }
        public override void SetResponseHeader(string key, string[] value)
        {
            this.response.headers.AddValue(key, value);
        }
        /// <summary>
        /// 设置状态码
        /// </summary>
        /// <param name="statusCode"></param>
        public override void SetResponseStatusCode(int statusCode)
        {
            this.response.statusCode = statusCode;
            if (this._serverType != ServerType.IsStatic)
            {
                this.enviroment["owin.ResponseStatusCode"] = this.response.statusCode;
            }
        }
        /// <summary>
        /// 模板渲染前函数，用于子类重写
        /// </summary>
        public override void Before()
        {

        }
        /// <summary>
        /// 输出字节流，用于输出二进制流，如图象，文件等。
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        public override async void Write(byte[] buffer, int offset, int count)
        {
            if (beforeWrite)
            {
                beforeWrite = false;
                if (_serverType != ServerType.IsStatic)
                {
                    IDictionary<string, string[]> headers = (IDictionary<string, string[]>)enviroment["owin.ResponseHeaders"];
                    foreach (var header in this.response.headers)
                    {
                        headers.AddValue(header.Key, header.Value);
                    }
                }
            }
            await contentStream.WriteAsync(buffer, 0, count);
        }
        /// <summary>
        /// 模板渲染后函数，用于子类重写
        /// </summary>
        public override void After()
        {

        }
        /// <summary>
        /// Environment过滤器
        /// </summary>
        public virtual bool EnvironmentFilter()
        {
            return true;
        }
        /// <summary>
        /// Request过滤器
        /// </summary>
        /// <returns></returns>
        public virtual bool RequestFilter()
        {
            return true;
        }
        /// <summary>
        /// 返回过滤器
        /// </summary>
        public virtual void ResponseFilter()
        {
            
        }
        /// <summary>
        /// 释放掉压缩流对象
        /// </summary>
        public override void Close()
        {
            if (compressMode == CompressMode.GZip || compressMode == CompressMode.Deflate)
            {
                this.contentStream.Dispose();
            }
            if (request.stream != null)
            {
                this.request.stream.Dispose();
            }
        }
        #endregion
    }
}